#火山翻译文档地址:
#https://www.volcengine.com/docs/4640/35107
#pip install --upgrade volcengine
import json
from volcengine.ApiInfo import ApiInfo
from volcengine.Credentials import Credentials
from volcengine.ServiceInfo import ServiceInfo
from volcengine.base.Service import Service

from urllib import request
from urllib import parse
import json,random,time
import hashlib
#用于读取项目目录下的yaml_name.db
import yaml  ,os,sys  ,json                             #第三方模块yaml          需要下载  是一个配置文件解析的第三方模块
project_dir_path=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  #项目路径
sys.path.append(project_dir_path)           #将项目路径添加到环境中   使得python可以导包
class 翻译_class:
    def __init__(self,project_dir_path,default_name='_default'):
        self.default=default_name
        #config目标文件夹
        self.config_dir=project_dir_path+os.sep+'config'
        #翻译结果历史存放位置
        self.翻译_data=project_dir_path+os.sep+'other'+os.sep+'翻译_data'
        try:os.makedirs(self.翻译_data)
        except:pass
    #读取目标语言历史翻译数据
    def read_data(self,to):
        path=self.翻译_data+os.sep+to+'.yaml'
        try:
            with open(path, 'r',encoding='utf-8') as f:
                data = yaml.load(f, Loader=yaml.FullLoader)
                return data
        except:
            return {}
    #保存目标历史数据
    def save_data(self,data,to='English'):
        path=self.翻译_data+os.sep+to+'.yaml'

        yaml_data = yaml.dump(data, allow_unicode=True, sort_keys=False, indent=4)  
        
        # 将YAML字符串写入文件  
        with open(path, 'w',encoding='utf-8') as yaml_file:  
            yaml_file.write(yaml_data)
    #读取default.yaml
    def read_default(self):
        path=self.config_dir+os.sep+self.default+'.yaml'
        with open(path, 'r',encoding='utf-8') as f:
            data = f.read()
        return data
    #保存为目标语言
    def write_language(self,data,laguage_name='中文'): 
        path=self.config_dir+os.sep+laguage_name+'.yaml'    
        print(path)     
        # 将YAML字符串写入文件  
        with open(path, 'w',encoding='utf-8') as f:  
            f.write(data)
    #查找结束
    def find_end(self,str_data,标识符='_____',start_idx=0,end=('"',"'")):
        # print(str_data)
        new_str=str_data[start_idx:]
        idx1=new_str.find(标识符)
        if idx1==-1:return False
        for i in range(idx1,len(new_str)):
            if new_str[i] in end:
                idx2=i
                break
        return start_idx+idx2,new_str[idx1:idx2]
    #func为翻译单词的函数
    def 翻译为其他语言(self,dct={'English':'en','にほん':'ja'},func=None,标识符='_____'):
        #获取默认配置
        default_config=self.read_default()
        #保存为中文
        self.write_language(default_config.replace(标识符,''),laguage_name='中文')
        #读取目标语言历史数据 以及初始化配置
        data_dct={}
        config_dct={}
        for key in dct:
            data_dct[key]=self.read_data(key)
            config_dct[key]=default_config

        #循环查询带有标识符的字符串
        start_idx=0
        while 1:
            res=self.find_end(default_config,start_idx=start_idx)
            if res is False:break
            start_idx,old_find_str=res
            find_str=old_find_str[len(标识符):]
            for key in dct:
                历史数据dict=data_dct[key]
                #先从历史数据中获取数据
                get_language=历史数据dict.get(find_str)
                #历史数据里没有  再从翻译中获取
                if get_language is None:
                    print(f'准备翻译({dct[key]})',find_str)
                    time.sleep(5)
                    #翻译数据

                    get_language=func(find_str,dct[key])
                    print(f'{find_str} 翻译为:',get_language)
                    #保存数据
                    历史数据dict[find_str]=get_language
                else:
                    print(f'{find_str} 翻译为:',get_language)
                
                #替换数据
                idx1=config_dct[key].find(old_find_str)
                # if find_str=='添加加工罐':input(str(['添加加工罐',idx1,config_dct[key][idx1:idx1+30]]))
                config_dct[key]=config_dct[key][:idx1]+get_language+config_dct[key][idx1+len(old_find_str):]
                # if len(default_config)>len(config_dct[key])+500:input(str([config_dct[key],old_find_str]))

        #保存历史数据 和 配置文件
        for key in dct:
            print('开始保存',key)
            self.save_data(data_dct[key],to=key)
            self.write_language(config_dct[key],laguage_name=key)
        # for save_name in dct:

#翻译
def translate_Word(en_str,to_name='ja'):
    pass

    k_access_key = 'AKLTZTY5YzFhYzhhNDQwNDcwODk3NGYxNDA3ODYzMDg2YjA' # https://console.volcengine.com/iam/keymanage/
    k_secret_key = 'WW1VNU5UWTBORGc0TXpSa05HRmpNV0ppWW1ReE9EWTRNR1ExWTJZMU5qRQ=='
    k_service_info = \
        ServiceInfo('translate.volcengineapi.com',
                    {'Content-Type': 'application/json'},
                    Credentials(k_access_key, k_secret_key, 'translate', 'cn-north-1'),
                    5,
                    5)
    k_query = {
        'Action': 'TranslateText',
        'Version': '2020-06-01'
    }
    k_api_info = {
        'translate': ApiInfo('POST', '/', k_query, {}, {})
    }
    service = Service(k_service_info, k_api_info)
    body = {
        'TargetLanguage': to_name,
        'TextList': [en_str],
    }
    res = service.json('translate', {}, json.dumps(body))
    res=json.loads(res)
    try:
        return res['TranslationList'][0]['Translation']
    except:
        print('???',res)
        raise Exception('...')
if __name__=='__main__':
    # print(translate_Word('老挝','lo'))
    # #读取当前使用的配置
    翻译_obj=翻译_class(project_dir_path)
    翻译_obj.翻译为其他语言(dct={
        'English':'en',
        'にほん':'ja',
        'ປະເທດລາວ':'lo',
    },func=translate_Word,标识符='_____')